package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.beans.Tools;
import ca.ubc.icapture.genapha.forms.AnalysisFilesForm;
import icapture.SQLMgr;
import icapture.beans.DB.Result;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public abstract class AnalysisFilesAction extends Action
{

    protected final Result result = new Result();

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    {
        ActionForward forward;
        final AnalysisFilesForm analysisForm = (AnalysisFilesForm) form;

        try
        {
            // Init result
            result.setUser(Tools.getUsername(request));
            result.setStatus("processing");
            result.setTime(new Timestamp(System.currentTimeMillis()));
            SQLMgr.insertResult(result);
            request.getSession().setAttribute("resultid", result.getResultID());

            // Launch a new thread to process the request
            new Thread()
            {

                @Override
                public void run()
                {
                    processRequest(analysisForm);
                }
            }.start();

            forward = mapping.findForward("success");
        }
        catch (Exception e)
        {
            result.setStatus("Error");
            SQLMgr.updateResult(result);
            e.printStackTrace();
            forward = mapping.findForward("error");
        }

        return forward;
    }

    /**
     * Handles page specific export process
     * @param form The ActionForm for each page
     */
    protected abstract void processRequest(AnalysisFilesForm form);
}
